package clusteringAlg;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
//import java.util.ArrayList;
import java.util.List;

import org.opencv.core.CvType;
import org.opencv.core.Mat;
import org.opencv.core.Size;
import org.opencv.highgui.Highgui;
import org.opencv.imgproc.Imgproc;

import com.atul.JavaOpenCV.Imshow;


public class Help {
	
	/**
	 * @param s
	 */
	public Help(Size s) {
		super();
		this.s = s;
	}

	Size s;
	
	/**
	 * @return the s
	 */
	public Size getS() {
		return s;
	}

	/**
	 * @param s the s to set
	 */
	public void setS(Size s) {
		this.s = s;
	}

	public void showImages( List<Sample> images){
		for (Sample m: images){
			Imshow im = new Imshow("Title");
	    	im.showImage(m.getImage());
		}
	}
	
	public void showImage( Sample image){

		Imshow im = new Imshow("Title");
    	im.showImage(image.getImage());
	}
	
	public void CreateDir(String dir){
		File f = new File(dir);
		
		if (!f.exists()) {
		    boolean result = f.mkdir();  

		     if(!result) {    
		       System.out.println("DIR not created"); 
		       CreateDir(f.getParentFile().getAbsolutePath());
		       CreateDir(dir);
		     }
		 }
	}
	
	public void savePoseIntoFile (String folderName, List<Sample> images){
		
		this.CreateDir(folderName);
		
		PrintWriter writer = null;
		
		try {
			writer = new PrintWriter(folderName + "/info.txt", "UTF-8");
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		for (Sample m: images){			
			writer.println(m.getPose());
		}
		
		writer.close();
	}
	
	public void saveImages(String folderName, List<Sample> images){
		
		int counter=0;
		String path;
		//File f = new File(folderName);
	
		this.CreateDir(folderName);
		
		for (Sample m: images){
			path = new String(folderName + "/" + counter++ + ".jpg");
			
			try {
				Highgui.imwrite(path, m.getImage());
			}
			catch (Error e) {
				System.err.println("Exception: " + e.getMessage());
			}
		}
	}
	
	public int fileCount(String path){
		
		File folder = new File(path);
		int count = 0;
		
		for (final File file : folder.listFiles()) {
			if (file.isDirectory()) {
				count = fileCount(file.getAbsolutePath());
			} else {
				count++;
			}
	    }
		
		return count;
	}
	
	public void eraseDirContent(String path){
		
		File folder = new File(path);
		
		for (final File file : folder.listFiles()) {
			try {
				if (file.isDirectory()) {
					eraseDirContent(file.getAbsolutePath());
				} else {

					if (file.delete()) {
						System.out.println(file.getName() + " is deleted!");
					} else {
						System.out.println("Delete operation is failed.");
					}

				}
			} catch (Exception e) {

				e.printStackTrace();

			}
	    }
	}
	
	public void saveImages(String folderName, int index, List<Sample> images){
		
		int counter=0;
		String path;
		//File f = new File(folderName);
		
		this.CreateDir(folderName);
	
		for (Sample m: images){
			path = new String(folderName + "/" + index + "_" + counter++ + "_pose" + m.getPose() + ".jpg");
			
			try {
				Highgui.imwrite(path, m.getImage());
			}
			catch (Error e) {
				System.err.println("Exception: " + e.getMessage());
			}
		}
	}

	public void listFilesForFolder(final File folder, List<Person> persons, FaceDB db) {
		
		if (db == FaceDB.EURECOM){		
			EurecomDatabase(folder, persons);
		}
		if (db == FaceDB.PIE){
			PieDatabase(folder, persons);
		}
	}
	
	void EurecomDatabase(final File folder, List<Person> persons){
		int id;
		boolean isExist=false;
		
	    for (final File fileEntry : folder.listFiles()) {
	    	isExist=false;
	    	Person pers = null;
	    			
	        if (fileEntry.isDirectory()) {
	        	EurecomDatabase(fileEntry, persons);
	        } else {
	        	
	        	String s[] = fileEntry.getName().split("_");
	        	id = Integer.parseInt(s[1]);
	        	
	        	for (Person p:persons){
	        		if (p.id == id){
	        			pers = p;
	        			isExist = true;
	        			break;
	        		}
	        	}
	        	
	        	if (!isExist){
	        		pers = new Person(id);
	        		persons.add(pers);
	        	}
	        	
	        	Mat m = Highgui.imread(fileEntry.getAbsolutePath());
	        	Imgproc.cvtColor( m, m, Imgproc.COLOR_BGR2GRAY);
	        	Imgproc.equalizeHist(m, m);

	        	if (!this.s.equals(m.size()))
	        		Imgproc.resize(m, m, this.s);
	        	
	        	m.convertTo(m, CvType.CV_64FC3);
	        	
	        	Sample sample = new Sample(m, -1);
	        	
        		pers.AddSample(sample);
        		
	        }
	    }
	}
	
	void PieDatabase(final File folder, List<Person> persons){
		
		int id;
		boolean isExist=false;
		
	    for (final File fileEntry : folder.listFiles()) {
	    	isExist=false;
	    	Person pers = null;
	    			
	        if (fileEntry.isDirectory()) {
	        	PieDatabase(fileEntry, persons);
	        } else {
	        	
	        	String s[] = fileEntry.getName().split("_");
	        	id = Integer.parseInt(s[0]);
	        	
	        	for (Person p:persons){
	        		if (p.id == id){
	        			pers = p;
	        			isExist = true;
	        			break;
	        		}
	        	}
	        	
	        	if (!isExist){
	        		pers = new Person(id);
	        		persons.add(pers);
	        	}
	        	
	        	Mat m = Highgui.imread(fileEntry.getAbsolutePath());
	        	Imgproc.cvtColor( m, m, Imgproc.COLOR_BGR2GRAY);
	        	Imgproc.equalizeHist(m, m);
	        	
	        	if (!this.s.equals(m.size()))
	        		Imgproc.resize(m, m, this.s);
	        	
	        	m.convertTo(m, CvType.CV_64FC3);
	        	
	        	s = fileEntry.getParentFile().getName().split("_");
	        	s[0] = s[0].replace("Pose", "");
	        	
	        	Sample sample = new Sample(m, Integer.parseInt(s[0]));
	        	
        		pers.AddSample(sample);
        		
	        }
	    }
	    
	}

	public void log(String str, SampleSelectorWorker selector) {
		
		this.CreateDir(str);
		
		try {
		    PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(str + "/log.csv", true)));
		    out.println(selector.CreateLog());
		    out.close();
		} catch (IOException e) {
		    //exception handling left as an exercise for the reader
		}
		
	}
	
}
